import os
import yaml

from common.utils import read_yaml
from core.request_handler import RequestHandler
from common.logger import logger


class UserOperations:

    def __init__(self, config_file, data_file):

        # 打印当前工作目录以帮助调试
        print(f"当前工作目录: {os.getcwd()}")

        # 生成绝对路径
        base_dir = os.path.dirname(os.path.abspath(__file__))  # 获取当前文件的绝对路径
        config_file_path = os.path.join(base_dir, '..', 'config', config_file)
        data_file_path = os.path.join(base_dir, '..', 'data', data_file)

        # 正确解析路径
        config_file_path = os.path.abspath(config_file_path)
        data_file_path = os.path.abspath(data_file_path)

        print(f"配置文件路径: {config_file_path}")
        print(f"数据文件路径: {data_file_path}")

        # 读取配置文件
        with open(config_file_path, 'r') as file:
            config = yaml.safe_load(file)
        self.base_url = config['base_url']  # 设置基础URL
        self.data_file = data_file_path  # 设置数据文件路径
        self.request_handler = RequestHandler(self.base_url)  # 初始化请求处理器
        # 记录base_url，便于后续跟踪或调试
        logger.info(f"base_url: {self.base_url}")
        self.token = None  # 初始化token为空

    # def login(self, mobile, code, grantType, terminalType):
    def login(self,payload ):
        # 从 YAML 文件中读取配置
        # config = read_yaml('data/test_data.yaml')
        # payload = {
        #     "mobile": mobile,
        #     "code": code,
        #     "grantType": grantType,
        #     "terminalType": terminalType
        # }
        # logger.info(f"登录参数: {payload}")
        headers = {
            "Authorization": "OTU0dXF0MG5zamVoZ2l4dGEzN2luMDg1Ond6MW51enB4amQ1bG5xN3JhM2V3aHFzcHhuMnBnZHQy",
            "Applicationid": "464781535210464262",
            "Butenantid": "439938383512058064",
            "Accept": "application/json, text/plain, */*",
            "Versiontype": "2",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
            "Content-Type": "application/json",
            "Host": "test-school-dl.workeredu.com",
            "Accept-Encoding": "gzip, deflate, br",
            "Connection": "keep-alive"
        }
        logger.info("********开始登录过程**************")
        response = self.request_handler.post_request('api/oauth/anyTenant/login', headers, json=payload)

        # 检查响应状态码
        if response.status_code == 200:
            response_json = response.json()
            if response_json["code"] == 0:
                # 提取 token
                token = response_json["data"].get("token")
                return {
                    "code": response_json["code"],
                    "msg": response_json["msg"],
                    "token": token
                }
            else:
                return {"code": response_json["code"], "msg": response_json["msg"], "token": None}
        else:
            logger.error(f"请求失败，状态码: {response.status_code}, 错误信息: {response.text}")
            return {"code": response.status_code, "msg": response.text, "token": None}

        #     else:
        #         return {"code": response_json["code"], "msg": response_json["msg"], "token": None}
        # else:
        #     return {"code": response.status_code, "msg": response.text, "token": None}

    # def login1(self):
    #     # 从数据文件中读取并加载用户登录信息
    #     with open(self.data_file, 'r') as file:
    #         # 使用yaml安全加载文件内容
    #         data = yaml.safe_load(file)
    #         # 提取登录信息作为负载
    #     payload = data['login1']
    #     logger.info(f"登录信息: {payload}")
    #     # headers = data['headers']
    #     headers = {
    #         "Authorization": "OTU0dXF0MG5zamVoZ2l4dGEzN2luMDg1Ond6MW51enB4amQ1bG5xN3JhM2V3aHFzcHhuMnBnZHQy",
    #         "Applicationid": "464781535210464262",
    #         "Butenantid": "439938383512058064",
    #         "Accept": "application/json, text/plain, */*",
    #         "Versiontype": "2",
    #         "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
    #         "Content-Type": "application/json",
    #         "Host": "test-school-dl.workeredu.com",
    #         "Accept-Encoding": "gzip, deflate, br",
    #         "Connection": "keep-alive"
    #     }
    #     logger.info("********开始登录过程**************")
    #     response = self.request_handler.post_request('api/oauth/anyTenant/login', headers, payload)
    #
    #     # 打印并存储 token
    #     self.token = ResponseHandler.extract_token(response)
    #     logger.info(f"登录响应: {response.json()}")
    #     logger.info(f"存储的 token: {self.token}")
    #
    #     return response
